package com.young.nyd.web;

import com.young.common.core.excel.ExcelExport;
import com.young.common.core.excel.ExcelImport;
import com.young.common.core.excel.IExcelExport;
import com.young.common.core.excel.IExcelImport;
import com.young.common.util.CommonUtil;
import com.young.common.util.Result;
import com.young.common.util.StringUtils;
import com.young.common.util.Page;
import com.young.interfaces.log.annotation.Log;
import com.young.nyd.model.LandMonitoringindex;
import com.young.nyd.model.LocalSample;
import com.young.nyd.service.ILandMonitoringindexService;
import com.young.nyd.service.ILocalSampleService;
import com.young.nyd.util.XzquUserController;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import static com.young.common.util.Result.buildFail;

/**
* 指标服务
* Created by  on 2018-11-4.
*/
@Controller
@RequestMapping("/nyd/landMonitoringindex")
public class LandMonitoringindexController {

    @Resource(name="landMonitoringindexService")
    ILandMonitoringindexService service;

    @Resource(name="localSampleService")
    ILocalSampleService sampleService;

    XzquUserController xzquUserController = new XzquUserController();

    /**
     * 获取数据列表
     * @param obj
     * @param request
     * @return
     */
    @Log("查询指标列表")
    @RequestMapping("/getList")
    @ResponseBody
    public Object getList(LandMonitoringindex obj, HttpServletRequest request) {
        String xzbm = xzquUserController.selectUserXZBM();
        if(xzbm == null){
            return  Result.build(Result.CodeEnum.SESSION_TIMEOUT);
        }else if(xzbm.equals("root")){

        }else {
            obj.setRegions(xzbm);
        }
        List<LandMonitoringindex> list = service.getList(obj);
        return new Result(list);
    }

    /**
     * 获取分页数据
     * @param obj
     * @param request
     * @return
     */
    @Log("分页查询指标列表")
    @RequestMapping("/getPage")
    @ResponseBody
    public Object getPage(LandMonitoringindex obj, HttpServletRequest request,String indicators,String sampleNumber) {
        String indicators1 = request.getParameter("indicators");
//        String sampleNumber = request.getParameter("sampleNumber");
        Page page = CommonUtil.getPageFromRequest(request);
        String xzbm = xzquUserController.selectUserXZBM();
        if(xzbm == null){
            return  Result.build(Result.CodeEnum.SESSION_TIMEOUT);
        }else if(xzbm.equals("root")){

        }else {
            obj.setRegions(xzbm);
        }
        List<LandMonitoringindex> list = service.getPage(obj, page);
        page.setData(list);
        return page;
    }

    /**
     * 获取单条数据
     * @param id
     * @param request
     * @return
     */
    @Log("查询指标")
    @RequestMapping("/get")
    @ResponseBody
    public Object get(String id, HttpServletRequest request) {
        LandMonitoringindex obj = service.get(id);
        return new Result(obj);
    }

    /**
     * 统计数量
     * @param obj
     * @param request
     * @return
     */
    @Log("统计指标数量")
    @RequestMapping("/count")
    @ResponseBody
    public Object count(LandMonitoringindex obj, HttpServletRequest request) {
        String xzbm = xzquUserController.selectUserXZBM();
        if(xzbm == null){
            return  Result.build(Result.CodeEnum.SESSION_TIMEOUT);
        }else if(xzbm.equals("root")){

        }else {
            obj.setRegions(xzbm);
        }
        return new Result(service.count(obj));
    }

    /**
     * 新增
     * @param obj
     * @param request
     * @return
     */
    @Log("新增指标")
    @RequestMapping("/insert")
    @ResponseBody
    public Object insert(LandMonitoringindex obj, HttpServletRequest request) {
        LocalSample sample = new LocalSample();
        sample.setSampleNumber(obj.getSampleNumber());
        List<LocalSample> list = sampleService.getList(sample);
        if(list.size()>0){
            if(list.size()==1){
              LandMonitoringindex landMonitoringindex = new LandMonitoringindex();
              landMonitoringindex.setIndicators(obj.getIndicators());
              landMonitoringindex.setSampleNumber(obj.getSampleNumber());
              List<LandMonitoringindex> list1 = service.getList(landMonitoringindex);
              if(list1.size()>0){
                  return new Result(1,"该指标已存在");
              }else{
                  String countyCode = request.getParameter("county");
                  String cityCode = request.getParameter("city");
                  String provinceCode = request.getParameter("province");
                  if (countyCode != null && !countyCode .equals("")){
                      obj.setRegions(countyCode);
                  }else if(cityCode != null && !cityCode .equals("")){
                      obj.setRegions(cityCode);
                  }else if(provinceCode != null && !provinceCode .equals("")){
                      obj.setRegions(provinceCode);
                  }else{
                      return buildFail("行政区划为空");
                  }
                  service.insert(obj);
                  return new Result();
              }

            }else{
                return new Result(1,"添加指标只能关联一个样品");
            }
        }else{
            return new Result(1,"添加指标必须要关联一个样品");
        }


    }

    /**
     * 修改
     * @param obj
     * @param request
     * @return
     */
    @Log("修改指标")
    @RequestMapping("/update")
    @ResponseBody
    public Object update(LandMonitoringindex obj, HttpServletRequest request) {
        if(obj.getDetectUnlack()==0 || obj.getDetectUnlack().equals("0")){
            service.update(obj);
            return new Result();
        }else{
            return new Result(-1,"信息已锁定，请联系省级管理员解除锁定！方能修改");
        }
    }

    /**
     * 锁定
     * @param ids
     * @param id
     * @param request
     * @return
     * @throws Exception
     */
    @Log("锁定地方监测指标结果")
    @RequestMapping("/lock")
    @ResponseBody
    public Object lock(String ids, String id, HttpServletRequest request) throws Exception{
        Result result = new Result();
        LandMonitoringindex s = new LandMonitoringindex();
        int i = 0;
        if(StringUtils.isNotBlank(ids)) {
            String[] idArr = ids.split(",");
            for(String id1 : idArr){
                s.setId(id1);
                s.setDetectUnlack(new Integer("1"));
                i += service.update(s);
            }
            if(i>=1){
                result.setCode(0);
            }else{
                result.setCode(-1);
                result.setInfo("锁定失败:待锁定编号无效!");
            }
        }else if(StringUtils.isNotBlank(id)){
            s.setId(id);
            s.setDetectUnlack(new Integer("1"));
            i = service.update(s);
            if(i>=1){
                result.setCode(0);
            }else{
                result.setCode(-1);
                result.setInfo("锁定失败:待锁定编号无效!");
            }
        }else{
            result.setCode(-1);
            result.setInfo("锁定失败:待锁定编号无效!");
        }
        return result;
    }

    /**
     * 解锁
     * @param ids
     * @param id
     * @param request
     * @return
     * @throws Exception
     */
    @Log("解锁地方监测指标结果")
    @RequestMapping("/unlock")
    @ResponseBody
    public Object unlock(String ids, String id, HttpServletRequest request) throws Exception{
        Result result = new Result();
        LandMonitoringindex s = new LandMonitoringindex();
        int i = 0;
        if(StringUtils.isNotBlank(ids)) {
            String[] idArr = ids.split(",");
            for(String id1 : idArr){
                s.setId(id1);
                s.setDetectUnlack(new Integer("0"));
                i += service.update(s);
            }
            if(i>=1){
                result.setCode(0);
            }else{
                result.setCode(-1);
                result.setInfo("解锁失败:待解锁编号无效!");
            }
        }else if(StringUtils.isNotBlank(id)){
            s.setId(id);
            s.setDetectUnlack(new Integer("0"));
            i = service.update(s);
            if(i>=1){
                result.setCode(0);
            }else{
                result.setCode(-1);
                result.setInfo("解锁失败:待解锁编号无效!");
            }
        }else{
            result.setCode(-1);
            result.setInfo("解锁失败:待解锁编号无效!");
        }
        return result;
    }

    /**
     * 删除
     * @param ids
     * @param id
     * @param request
     * @return
     */
    @Log("删除指标")
    @RequestMapping("/delete")
    @ResponseBody
    public Object delete(String ids, String id, HttpServletRequest request) {
        Result result = new Result();
        if(StringUtils.isNotBlank(ids)) {
            String[] idArr = ids.split(",");
            service.delete(idArr);
        }else if(StringUtils.isNotBlank(id)){
            service.delete(id);
        }else{
            result.setCode(-1);
            result.setInfo("删除失败:待删除编号无效!");
        }
        return result;
    }

    /**
     * 导入
     * @param file
     * @param request
     * @return
     */
    @Log("导入指标")
    @RequestMapping("/import")
    @ResponseBody
    public Object importExcel(MultipartFile file, HttpServletRequest request) {
        Result result = new Result();
        try {
            if (file != null && !file.isEmpty()) {
                //excel导入处理,返回excel中的数据集合
                IExcelImport ei = new ExcelImport(file);//将文件转为ExcelImport对象
                //从excel读取数据
                List<LandMonitoringindex> list = ei.getImportDataAsBean(LandMonitoringindex.class);
                if (list != null && list.size() > 0){
                    int num = service.batchInsert(list);//批量插入
                    result.setInfo("成功导入数据" + num + "条!");
                }else {
                    result.setCode(-1);
                    result.setInfo("导入失败:excel解析后结果为空!");
                }
            } else {
                result.setCode(-1);
                result.setInfo("导入失败:文件为空!");
            }
        } catch (IOException e) {
            e.printStackTrace();
            result.setCode(-1);
            result.setInfo("导入失败!");
        } catch (NoSuchMethodException e) {
            e.printStackTrace();
            result.setCode(-1);
            result.setInfo("导入失败!");
        } catch (Exception e) {
            e.printStackTrace();
            result.setCode(-1);
            result.setInfo("导入失败!");
        }
        return result;
    }

    /**
     * 导出
     * @param obj 查询参数
     * @param request
     * @param response
     * @throws Exception
     */
    @Log("导出指标")
    @RequestMapping("/export")
    public void exportExcel(LandMonitoringindex obj, HttpServletRequest request, HttpServletResponse response,String ids) throws Exception {
        List<LandMonitoringindex> list = new ArrayList<LandMonitoringindex>();
        if (ids != null && !"".equals(ids)) {
            String[] ids1 = ids.split(",");
            for (String id : ids1) {
                LandMonitoringindex u = service.get(id);
                list.add(u);
            }
        } else {
            String xzbm = xzquUserController.selectUserXZBM();
            if(xzbm == null){
                response.getWriter().write("行政区划，数据为空!");
            }else if(xzbm.equals("root")){

            }else {
                obj.setRegions(xzbm);
            }
            list = service.getList(obj);
        }
        if (list != null && list.size() > 0) {
            IExcelExport ee = new ExcelExport();
            ee.insertBeanList(list, LandMonitoringindex.class);
            ee.write2Response(response, "excel_" + System.currentTimeMillis() + ".xls");
        } else {
            response.getWriter().write("数据为空!");
        }
    }

}